import {
  Button,
  ConfigProvider,
  Descriptions,
  Drawer,
  Dropdown,
  Menu,
  Modal,
  Popconfirm,
  Space,
  Table
} from 'antd';

import React, { useEffect, useRef, useState } from 'react';
import { ListForm } from './config';
import { Buttongroup, FeedForm, NewForm, STEPS } from './config';
import http from '@/services/request';
import zhCN from 'antd/es/locale/zh_CN';
import store from '@/pages/home/store';
import { action11, action3 } from '@/pages/home/createAction';
import { openNotification } from '@/components/Pop';

function Instore() {
  //编辑单号的id
  const [feedid, setFeedid] = useState(0);
  //table的数据
  const [dataSource, setDataSource]: any = useState();
  //改变步骤渲染页面
  const [step, setStep] = useState('新增入库记录');
  //改变进度条的进度
  const [current, setCurrent] = useState(2);
  //详情功能定位id
  const [Drawerid, setDrawerid]: any = useState([]);
  //抽屉开关
  const [DrawerVisible, setDrawerVisible] = useState(false);
  //新增入库编号--ref-兄弟组件间通信，靠父子间实现
  const InNumberref: any = useRef();
  //新增饲料入库
  const Instoreref: any = useRef();
  //入库单号的列表表单
  const listref: any = useRef();
  //获取饲料编号
  const [feedOptions, setFeedOptions]: any = useState();
  // 控制对话框显示（新增）
  const [addModalVisible, setAddModalVisible] = useState(false);
  //入库记录的内容
  useEffect(() => {
    http.get('/goods/chicken/feedInFarming/list/1/100').then((res) => {
      const data = res.data.records || [];
      setDataSource(data);
      //获取饲料编号
      http.get(`/goods/chicken/feedInfoFarming/list/1/30`).then((res) => {
        const FeedNumberOptions: Number[] = [];
        res.data.records.forEach((i: { feedNumber: string }) => {
          FeedNumberOptions.push(Number(i.feedNumber));
        });
        setFeedOptions(FeedNumberOptions);
      });
    });
  }, []);

  const FormColumns: any = [
    {
      title: '入库单号',
      dataIndex: 'inNumber',
      key: 'inNumber',
      sorter: (a: any, b: any) => a.inNumber - b.inNumber,
      width: 100
    },
    {
      title: '批次编号',
      dataIndex: 'batch',
      key: 'batch',
      width: 100
    },
    {
      title: '入库时间',
      dataIndex: 'inDate',
      key: 'inDate',
      width: 200
    },

    {
      title: '仓库接收人名称',
      dataIndex: 'receiverName',
      key: 'receiverName',

    },
    {
      title: '仓库接收人电话',
      dataIndex: 'receiverPhone',
      key: 'receiverPhone'
    },
    {
      title: '供应商名称',
      dataIndex: 'supplierName',
      key: 'supplierName'
    },

    {
      title: '供应商电话',
      dataIndex: 'supplierNumber',
      key: 'supplierNumber'
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 150,
      render: (_: any, record: { id: number }) => (
        <Space>
          <a onClick={() => edit(record)}>编辑</a>
          <Popconfirm
            title="确定删除?"
            okText="确认"
            cancelText="取消"
            // cancelButtonProps={{ size: 'middle' }}
            onConfirm={() => {
              http
                .delete(`/goods/chicken/feedInFarming/show/detail/${record.id}`)
                .then(() => {
                  const newData = dataSource.filter(
                    (item: { id: any }) => item.id !== record.id
                  );
                  setDataSource(newData);
                });
            }}
          >
            <a style={{ color: '#ff4d4f' }}>删除</a>
          </Popconfirm>
          <Dropdown overlay={menu(record)}>
            <a onClick={(e) => e.preventDefault()}>···</a>
          </Dropdown>
        </Space>
      ),
      fixed: 'right'
    }
  ];
  const indexTable = {
    pagination: {
      //每页 10 条项目
      defaultPageSize: 10,
      //自定义每页显示数目
      showSizeChanger: true,
      //自定义每页显示项目的选项
      pageSizeOptions: ['5', '10', '15'],
      // 输入指定页码跳页
      showQuickJumper: true,
      //全部项目数（最好可以用变量表示，与实际项目数关联）
      total: dataSource?.length
    }
  };
  const menu = (item: any) => (
    <Menu
      items={[
        {
          key: 0,
          label: (
            <Button
              type="primary"
              onClick={(e: any) => {
                showDrawer(item);
              }}
            >
              详情
            </Button>
          )
        },

        {
          key: 2,
          label: (
            <Button
              onClick={function () {
                window.print();
              }}
            >
              打印
            </Button>
          )
        }
      ]}
    />
  );
  //详情--抽屉
  const showDrawer = (data: any) => {
    setDrawerVisible(true);

    http
      .get(`/goods/chicken/feedInFarming/show/detail/${data.inNumber}`)
      .then((res) => {
        store.dispatch(action11(data.inNumber));
        setDrawerid(res.data);
      });
  };

  const onDraweClose = () => {
    setDrawerVisible(false);
  };
  //编辑
  const edit = (record: any) => {
    setAddModalVisible(true);
    setFeedid(record.id);
    //这里必须单单setField..会报错："表单还没挂载调用了setFieldsValue",应该用异步，设一个定时器
    setTimeout(() => {
      listref.current.setFieldsValue({
        ...record,
        inDate: record.inDate
      });
      store.dispatch(action3('编辑'));
    }, 0);
  };
  //编辑modal框
  // 对话框确认
  const handleAddModalOk = () => {
    setAddModalVisible(false);
    //如果id存在--就是修改
    if (store.getState().name === '编辑') {
      const newedited = listref.current.getFieldsValue();
      http
        .put(`/goods/chicken/feedInFarming/update//${feedid}`, {
          ...newedited,
          inDate: newedited.inDate,
          inNumber: Number(newedited.inNumber)
        })
        .then(() => {
          setTimeout(() => {
            openNotification('top', '修改成功！');
          }, 0);
          http
            .get('/goods/chicken/feedInFarming/list/1/10')
            .then((res: { data: { records: any } }) =>
              setDataSource(res.data.records)
            );
        })
        .catch(() => {
          return setTimeout(() => {
            openNotification('bottom', '修改失败！');
          }, 0);
        });
    }
  };
  // 对话框取消
  const handleAddModalCancel = () => {
    setAddModalVisible(false);
  };
  return (
    <div>
      <STEPS current={current}></STEPS>
      <div style={{ margin: ' 40px 0' }}>
        {step === '新增订单编号' ? <NewForm InNumberref={InNumberref} /> : ''}
      </div>
      <div style={{ margin: ' 40px 0' }}>
        {step === '新增饲料入库' ? (
          <FeedForm Instoreref={Instoreref} feedOptions={feedOptions} />
        ) : (
          ''
        )}
      </div>
      <div style={{ margin: ' 40px 0' }}>
        {step === '新增入库记录' ? (
          <ConfigProvider locale={zhCN}>
            {/*   <SearchSelector dataSource={(e: any) => setDataSource(e)
          } style={{ float: 'right' }}></SearchSelector> */}
            <Table
              dataSource={dataSource}
              columns={FormColumns}
              scroll={{ x: 1300 }}
              pagination={indexTable.pagination}
              rowKey={(i: { id: any }) => i.id}
            />
          </ConfigProvider>
        ) : (
          ''
        )}
        <Modal
          width={'600px'}
          bodyStyle={{
            display: 'flex',
            height: '500px',
            flexDirection: 'column-reverse'
          }}
          title="编辑入库单号"
          visible={addModalVisible}
          onOk={handleAddModalOk}
          onCancel={handleAddModalCancel}
        >
          <ListForm listref={listref}></ListForm>
        </Modal>
        {/* 订单编号，客户名 创建时间  件数 只数 重量 提货日期 提货人 */}
        <Drawer
          placement="right"
          onClose={onDraweClose}
          visible={DrawerVisible}
          title={`入库单号${store.getState().Number}信息`}
          width={'500px'}
        >
          {Drawerid.map((i: any, index: number) => (
            <Descriptions
              title={`第${index + 1}小单`}
              bordered
              style={{ width: '450px' }}
            >
              <Descriptions.Item label="饲料名称">
                {i.feedName}
              </Descriptions.Item>
              <Descriptions.Item label="饲料编号">
                {i.feedNumber}
              </Descriptions.Item>
              <Descriptions.Item label="库存信息">
                {i.inventory}
              </Descriptions.Item>
              <Descriptions.Item label="单价">{i.price}</Descriptions.Item>
              <Descriptions.Item label="库存数量">
                {i.quantity}
              </Descriptions.Item>
              <Descriptions.Item label="备注">{i.remark}</Descriptions.Item>
              <Descriptions.Item label="计量单位">{i.unit}</Descriptions.Item>
              <Descriptions.Item label="规格">
                {i.specification}
              </Descriptions.Item>
              <Descriptions.Item label="总价">{i.totalPrice}</Descriptions.Item>
            </Descriptions>
          ))}
        </Drawer>
      </div>
      <div>
        {
          <div>
            <Buttongroup
              setStep={(a: React.SetStateAction<string>) => setStep(a)}
              setCurrent={(a: number) => setCurrent(a)}
              switchstep={step}
              InNumberref={InNumberref}
              Instoreref={Instoreref}
            ></Buttongroup>
          </div>
        }
      </div>
    </div>
  );
}

export default Instore;
